<?php
namespace Home\Controller;
/**
 * 商品控制器
 */
class GoodsController extends BaseController {


	//云购商品管理
	public function yungoods(){
		$this->isShopLogin();
		$USER = session('WST_USER');
		//获取商家商品分类
		$m = D('Home/ShopsCats');
		$this->assign('shopCatsList',$m->queryByList($USER['shopId'],0));
		$shopId = $USER['shopId'];
		$model = new \Think\Model();
		$sql = "select count(*) as counts from __PREFIX__shoplist where shop_id={$shopId} and q_showtime='N' and `q_end_time` is null";
		$totalRows = current($model->query($sql))['counts'];
		$page = new \Think\Page($totalRows,C('PAGE_SIZE'));
		$limit = 'limit '.$page->firstRow.','.$page->listRows;
		$sql = "select pos,renqi,isbest,q_showtime,canyurenshu,shenyurenshu,qishu,maxqishu,thumb,id,sid,shop_id,title,money,yunjiage,zongrenshu from __PREFIX__shoplist where shop_id={$shopId} and q_showtime='N' and `q_end_time` is null order by time desc $limit";
		$this->assign('list',$model->query($sql));
		$this->assign('page',$page->show());
		$this->assign('pageTotal',$page->totalPages);
    	$this->assign("shopCatId2",I('shopCatId2'));
    	$this->assign("shopCatId1",I('shopCatId1'));
    	$this->assign("goodsName",I('goodsName'));
		$this->display('Yungo/list');
	}

	//往期商品
	public function qishulist(){
		$shopid=intval($_GET['gid']);
		if (!$shopid) $this->_empty('Goods','参数错误');
		$model = new \Think\Model();
		$info = $model->query("select * from `__PREFIX__shoplist` where `id` = '$shopid' LIMIT 1");
		if (empty($info)){
			$this->_empty('Goods','商品不存在');
		}
		$info = current($info);
		$num=20;
		$total=$model->query("select count(*) as counts from `__PREFIX__shoplist` where `sid`='{$info['sid']}' and `shop_id`='{$info['shop_id']}'");
		$total = $total[0]['counts'];
		$qishu=$model->query("select * from `__PREFIX__shoplist` where `sid`='{$info['sid']}' and `shop_id`='{$info['shop_id']}' order by `qishu` DESC");
		$this->list = $qishu;
		$this->display('Yungo/qishulist');
	}

	//删除云购商品
	public function yundelete(){
		$shopid=intval($_GET['gid']);
		if (!$shopid) $this->_empty('Goods','参数错误');
		$model = new \Think\Model();
		$info = $model->query("SELECT id,sid,codes_table FROM `__PREFIX__shoplist` WHERE `id` = '$shopid'");
		if(!$info){
			$this->_empty('Goods','商品不存在');
		}
		$info = current($info);
		$model->startTrans();
		$id = $info['id'];
		$sid = $info['sid'];
		$table = $info['codes_table'];
		$q1 = $model->execute("DELETE FROM `__PREFIX__{$table}` WHERE `s_id` = '$id'");
		$q2 = $model->execute("DELETE FROM `__PREFIX__shoplist` WHERE `id` = '$id' LIMIT 1");
		$q3 = $model->execute("DELETE FROM `__PREFIX__member_go_record` WHERE `shopid` = '$id'");
		if ($q1 && $q2 && $q3){
			$model->commit();
			$this->_empty('Goods','删除商品成功');
		}else{
			$model->rollback();
			$this->_empty('Goods','删除商品失败');
		}
	}

	//重置价格
	public function yunsetmoney(){
		$this->isShopLogin();
		$USER = session('WST_USER');
		$goodsId = intval($_GET['gid']);
		if (!$goodsId) $this->_empty('Goods','参数错误');
		$model = new \Think\Model();
		$model->startTrans();
		$shopinfo = $model->query("SELECT * FROM `__PREFIX__shoplist` where `id` = '$goodsId' for update");
		$shopinfo = current($shopinfo);
		if(!$shopinfo || !empty($shopinfo['q_uid'])){
			$this->_empty('Goods','商品不存在');
		}

		if(isset($_POST['money']) || isset($_POST['yunjiage'])){
			$new_money = abs(intval($_POST['money']));
			$new_one_m = abs(intval($_POST['yunjiage']));
			if (!$new_money || !$new_one_m){
				$this->ajaxReturn(array('status' => 0,'msg' => '价格填写错误!'));
			}
			if($new_one_m > $new_money){
				$this->ajaxReturn(array('status' => 0,'msg' => '单人次购买价格不能大于商品总价格!'));
			}
			if(($new_one_m == $shopinfo['yunjiage']) && ($new_money == $shopinfo['money'])){
				$this->ajaxReturn(array('status' => 0,'msg' => '价格没有改变!'));
			}
			$table = $shopinfo['codes_table'];
			$model->startTrans();

			$q1 = true;
			$count = M('member_go_record')->where(array('shopid' => $goodsId))->count();
			if ($count){
				$q1 = $model->execute("DELETE FROM `__PREFIX__member_go_record` WHERE `shopid` = '$goodsId'");
			}
			$q2 = $model->execute("DELETE FROM `__PREFIX__{$table}` WHERE `s_id` = '$goodsId'");
			$zongrenshu = ceil($new_money/$new_one_m);
			$q3 = content_get_go_codes($zongrenshu,3000,$goodsId);
			$q4 = $model->execute("UPDATE `__PREFIX__shoplist` SET
					`canyurenshu` = '0',
					`zongrenshu` = '$zongrenshu',
					`money` = '$new_money',
					`yunjiage` = '$new_one_m',
					`shenyurenshu` = `zongrenshu`
					where `id` = '$goodsId'");
			if($q1 && $q2 && $q3 && $q4){
				$model->commit();
				$this->ajaxReturn(array('status' => 1,'msg' => '更新成功!'));
			}else{
				$model->rollback();
				$this->ajaxReturn(array('status' => 0,'msg' => '更新失败!'));
			}
		}
		$this->assign('shopinfo',$shopinfo);
		$this->assign('prev_url',$_SERVER['HTTP_REFERER']);
		$this->display('Yungo/setmoney');
	}

	private function extPdata(){
		$data = array();
		$data['title'] = I('post.goodsName');
		$data['title2'] = I('post.title2');
		$data['mall_cateid'] = intval($_POST['goodsCatId1']);
		$data['mall_cateid2'] = intval($_POST['goodsCatId2']);
		$data['mall_cateid3'] = intval($_POST['goodsCatId3']);
		$data['shop_cateid'] = intval($_POST['shopCatId1']);
		$data['shop_cateid2'] = intval($_POST['shopCatId2']);
		$data['isbest'] = intval($_POST['isBest']);
		$data['renqi'] = intval($_POST['isHot']);
		$data['pos'] = intval($_POST['isRecomm']);
		$data['yunjiage'] = intval($_POST['yunjiage']);
		$data['money'] = intval($_POST['shopPrice']);
		$data['maxqishu'] = intval($_POST['maxqishu']);
		$data['brandid'] = intval($_POST['brandId']);
		$data['description'] = I('post.goodsSpec');
		$data['keywords'] = I('post.goodsKeywords');
		$data['content'] = I('post.goodsDesc');
		$data['thumb'] = I('post.goodsThumbs');
		$data['picarr'] = I('post.gallery');
		return $data;
	}

	//修改商品
	public function yunedit(){
		if (IS_AJAX){
			$data = $this->extPdata();
			$data['id'] = intval($_POST['id']);
			unset($data['money']);
			unset($data['yunjiage']);
			if (empty($data['id']))  $this->ajaxReturn(array('status' => '-99','msg' => '商品不存在'));
			if (empty($data['title'])) $this->ajaxReturn(array('status' => '-99','msg' => '商品标题不能为空'));
			if (empty($data['maxqishu']))  $this->ajaxReturn(array('status' => '-99','msg' => '最大期数不能为空'));
			if (empty($data['thumb']))  $this->ajaxReturn(array('status' => '-99','msg' => '请上传缩略图'));
			if (empty($data['mall_cateid'])) $this->ajaxReturn(array('status' => '-99','msg' => '请选择商城分类'));
			if (empty($data['shop_cateid'])) $this->ajaxReturn(array('status' => '-99','msg' => '请选择店铺分类'));
			if (M('shoplist')->save($data)){
				$this->ajaxReturn(array('status' => '1','msg' => ''));
			}
			$this->ajaxReturn(array('status' => '0','msg' => ''));
		}else{
			$this->isShopLogin();
			$USER = session('WST_USER');
			$goodsId = intval($_GET['gid']);
			$object = M('Shoplist')->where(array('id' => $goodsId))->find();
			if (!$object) $this->_empty('Goods','商品不存在');
			if (!empty($object['q_end_time'])){
				$this->_empty('Goods','已揭晓的商品不能修改');
				exit;
			}
			//获取商品分类信息
			$m = D('Home/GoodsCats');
			$this->assign('goodsCatsList',$m->queryByList());
			//二级分类
			$this->assign('goodsCatsList2',$m->queryByList($object['mall_cateid']));
			//三级分类
			$this->assign('goodsCatsList3',$m->queryByList($object['mall_cateid2']));

			//获取商家商品分类
			$m = D('Home/ShopsCats');
			$this->assign('shopCatsList',$m->queryByList($USER['shopId'],0));
			//二级分类
			$this->assign('shopCatsList2',$m->queryByList($USER['shopId'],$object['shop_cateid']));
			//牌品列表
			$this->assign('brandlist', M('brands')->select());
			if (!empty($object['picarr'])){
				$arr = explode(',', $object['picarr']);
				if (!empty($arr)){
					$gallery = array();
					foreach ($arr as $key => $value){
						$imgs = explode('@', $value);
						@$gallery[] = array('goodsThumbs' => $imgs[1],'goodsImg' => $imgs[0]);
					}
				}
			}
			$object['gallery'] = $gallery;
			$this->assign('object', $object);
			$this->display('Yungo/yunedit');
		}
	}

	//云购商品设为人气
	public function yunsetrenqi(){
		if (IS_AJAX){
			$User = session('WST_USER');
			if (empty($User)){
				$this->ajaxReturn(array('status' => 0));
			}
			$goodsId = intval($_POST['gid']);
			if (!$goodsId) $this->ajaxReturn(array('status' => 0,'msg'=>'商品不存在'));
			$where = array('id' => $goodsId);
			if (M('Shoplist')->where($where)->setField('renqi',1)){
				$this->ajaxReturn(array('status' => 1));
			}else{
				$this->ajaxReturn(array('status' => 0,'msg' => '操作失败'));
			}
		}else{
			$this->_empty('Goods');
		}
	}

	//新增云购商品
	public function addgoods(){
		if (IS_AJAX){
					$User = session('WST_USER');
			if (empty($User)){
				$this->ajaxReturn(array('status' => 0));
			}
			$data = $this->extPdata();
			if (empty($data['title'])) $this->ajaxReturn(array('status' => '-99','msg' => '商品标题不能为空'));
			if (empty($data['money'])) $this->ajaxReturn(array('status' => '-99','msg' => '商品总价格不能为空'));
			if (empty($data['yunjiage']))  $this->ajaxReturn(array('status' => '-99','msg' => '单次价格不能为空'));
			if (empty($data['maxqishu']))  $this->ajaxReturn(array('status' => '-99','msg' => '最大期数不能为空'));
			if (empty($data['thumb']))  $this->ajaxReturn(array('status' => '-99','msg' => '请上传缩略图'));
			if (empty($data['mall_cateid'])) $this->ajaxReturn(array('status' => '-99','msg' => '请选择商城分类'));
			if (empty($data['shop_cateid'])) $this->ajaxReturn(array('status' => '-99','msg' => '请选择店铺分类'));
			//最大期数不能大于65535
			if ($data['maxqishu'] > 65535){
				$this->ajaxReturn(array('status' => '-99','msg' => '最大期数不能大于65535'));
			}
			//云购价格不能大于商品总价
			if ($data['yunjiage'] > $data['money']){
				$this->ajaxReturn(array('status' => '-99','msg' => '单次价格不能大于商品总价'));
			}

			if (D('Go/Shoplist')->insert($data)){
				$this->ajaxReturn(array('status' => 1));
			}else{
				$this->ajaxReturn(array('status' => 0));
			}
		}else{
			$this->isShopLogin();
			$USER = session('WST_USER');
			//获取商品分类信息
			$m = D('Home/GoodsCats');
			$this->assign('goodsCatsList',$m->queryByList());
			//获取商家商品分类
			$m = D('Home/ShopsCats');
			$this->assign('shopCatsList',$m->queryByList($USER['shopId'],0));
			//获取商品类型
			$m = D('Home/AttributeCats');
			$this->assign('attributeCatsCatsList',$m->queryByList());
			$this->display('Yungo/edit');
		}
	}

	//云购商品订单
	public function yunorder(){
		$this->isShopLogin();
		$order = 'time desc';
		if (isset($_GET['paixu'])){
			$paixu = trim($_GET['paixu']);
			switch ($paixu){
				case 'time1':
					$order = 'time desc';
					$this->time1 = 'selected="selected"';
					break;
				case 'time2':
					$order = 'time asc';
					$this->time2 = 'selected="selected"';
					break;
				case 'num1':
					$order = 'gonumber desc';
					$this->num1 = 'selected="selected"';
					break;
				case 'num2':
					$order = 'gonumber asc';
					$this->num2 = 'selected="selected"';
					break;
				case 'money1':
					$order = 'moneycount desc';
					$this->money1 = 'selected="selected"';
					break;
				case 'money2':
					$this->money2 = 'selected="selected"';
					$order = 'moneycount asc';
					break;
			}
		}

		$where = isset($_GET['sng'])?trim($_GET['sng']):'';
		if(!$where){
			$list_where = " `status` LIKE  '%已付款%'";
			$this->sng = 'def';
		}elseif($where == 'zj'){
			//中奖
			$list_where = " `huode` != '0'";
			$this->sng = 'zj';
		}elseif($where == 'sendok'){
			//已发货订单
			$this->sng = 'sendok';
			$list_where = " `huode` != '0' and  `status` LIKE  '%已发货%'";
		}elseif($where == 'notsend'){
			//未发货订单
			$list_where = " `huode` != '0' and `status` LIKE  '%未发货%'";
			$this->sng = 'notsend';
		}elseif($where == 'ok'){
			//已完成
			$list_where = " `huode` != '0' and  `status` LIKE  '%已完成%'";
			$this->sng = 'ok';
			$this->sng = 'send';
		}elseif($where == 'del'){
			//已作废
			$list_where = " `status` LIKE  '%已作废%'";
		}elseif($where == 'gaisend'){
			//该发货
			$list_where = " `huode` != '0' and `status` LIKE  '%未发货%'";
		}elseif($where == 'shouhuo'){
			//该发货
			$list_where = " `status` LIKE  '%待收货%'";
		}

		if (isset($_POST['search_submit'])){
			$search = trim($_POST['search']);
			$paixu = $search;
			$list_where = '';
			$query = _htmtocode($_POST['query']);
			switch ($search){
				case 'ordersn':
					if (empty($query)) $this->_empty('goods','请输入订单号');
					$list_where = " `code`='{$query}'";
					$search1 = 'selected="selected"';
					break;
				case 'username':
					if (empty($query)) $this->_empty('goods','请输入用户名');
					$list_where = " `username`='{$query}'";
					$search2 = 'selected="selected"';
					break;
				case 'noprize':
					if (empty($query)){
						$list_where = " `huode`=0";
					}else{
						if (mb_substr($query,0, 2) == 'A1'){
							$list_where = " `code`='{$query}' and `huode`=0";
						}else{
							$list_where = " `username`='{$query}' and `huode`=0";
						}
					}
					$search3 = 'selected="selected"';
					break;
				case 'prize':
					if (empty($query)){
						$list_where = " `huode`!=0";
					}else{
						if (mb_substr($query,0, 2) == 'A1'){
							$list_where = " `code`='{$query}' and `huode`!=0";
						}else{
							$list_where = " `username`='{$query}' and `huode`!=0";
						}
					}
					$search4 = 'selected="selected"';
					break;
				case 'sendgoods':
					if (empty($query)){
						$list_where = " `huode`!=0 and `status` like '%未发货%'";
					}else{
						if (mb_substr($query,0, 2) == 'A1'){
							$list_where = " `code`='{$query}' `huode`!=0 and `status` like '%未发货%'";
						}else{
							$list_where = " `username`='{$query}' `huode`!=0 and `status` like '%未发货%'";
						}
					}
					$search3 = 'selected="selected"';
					break;
				case 'ingoods':
					if (empty($query)){
						$list_where = " `code`='{$query}' or `username`='{$query}' or `status` like '%已发货%'";
					}else{
						if (mb_substr($query,0, 2) == 'A1'){
							$list_where = " `code`='{$query}' `huode`!=0 and `status` like '%已发货%'";
						}else{
							$list_where = " `username`='{$query}' `huode`!=0 and `status` like '%已发货%'";
						}
					}
					$search4 = 'selected="selected"';
					break;
				case 'finish':
					if (empty($query)){
						$list_where = " `code`='{$query}' or `username`='{$query}' or `status` like '%已完成%'";
					}else{
						if (mb_substr($query, 0,2) == 'A1'){
							$list_where = " `code`='{$query}' and `status` like '%已完成%'";
						}else{
							$list_where = " `username`='{$query}' and `status` like '%已完成%'";
						}
					}
					$search5 = 'selected="selected"';
					break;
			}
		}

		$member_go_record = M('member_go_record');
		$TotalRows = $member_go_record->where($list_where)->count();
		$Page = new \Think\Page($TotalRows,10);
		$data = $member_go_record->where($list_where)->field('goucode',true)->limit($Page->firstRow.','.$Page->listRows)->order($order)->select();
		$this->assign('data',$data);
		$this->assign('page',$Page->show());

		$this->display('Yungo/yunorder');
	}

	public function dingdan(){
		$code=abs($_GET['gid']);
		$record = M('member_go_record')->where(array('id' => $code))->find();
		if(!$record)$this->_empty('goods','参数不正确');
		$uid= $record['uid'];
		$this->user_dizhi = M('user_address')->where(array('userId' => $uid,'isDefault' => 1))->find();
		if(isset($_POST['submit'])){
			$record_code =explode(",",$record['status']);
			$status = $_POST['status'];
			$company = $_POST['company'];
			$company_code = $_POST['company_code'];
			$company_money = floatval($_POST['company_money']);
			$code = abs(intval($_POST['code']));
			if(!$company_money){
				$company_money = '0.00';
			}else{
				$company_money = sprintf("%.2f",$company_money);
			}

			if($status == '未完成'){
				$status = $record_code[0].','.$record_code[1].','.'未完成';
			}
			if($status == '已发货'){
				$status = '已付款,已发货,待收货';
			}
			if($status == '未发货'){
				$status = '已付款,未发货,未完成';
			}
			if($status == '已完成'){
				$status = '已付款,已发货,已完成';
			}
			if($status == '已作废'){
				$status = $record_code[0].','.$record_code[1].','.'已作废';
			}

			$address_text = '';
			if (!empty($this->user_dizhi)){
				$sheng = M('areas')->where(array('areaId' => $this->user_dizhi['areaId1']))->getField('areaName');
				$shi = M('areas')->where(array('areaId' => $this->user_dizhi['areaId2']))->getField('areaName');
				$xian = M('areas')->where(array('areaId' => $this->user_dizhi['areaId3']))->getField('areaName');
				$address_text .= $sheng.' - '.$shi.' - '.$xian.' - ';
				$address_text .= " - 邮编:".$this->user_dizhi['postCode'];
				$address_text .= " - 收货人:".$this->user_dizhi['userName'];
				$address_text .= " - 手机:".$this->user_dizhi['userPhone'];
			}

			$ret = M('member_go_record')->where(array('id' => $code))->save(
					array('status' => $status,
						'company' => $company,
						'company_code' => $company_code,
						'company_money' => $company_money,
						'address' => $address_text
			));
			if($ret){
				$this->_empty('goods','更新成功');
			}else{
				$this->_empty('goods','更新失败');
			}
		}

		$this->user = M('Users')->where(array('userId' => $uid))->find();
		$this->go_time = $record['time'];
		$this->shop = M('shoplist')->where(array('id' => $record['shopid']))->find();
		$this->record = $record;
		$this->display('Yungo/dingdan');
	}

	/**
	 * 商品列表
	 */
    public function getGoodsList(){
   		$mgoods = D('Home/Goods');
   		$mareas = D('Home/Areas');
   		$mcommunitys = D('Home/Communitys');
   		//获取默认城市及县区
   		$areaId2 = $this->getDefaultCity();
   		$districts = $mareas->getDistricts($areaId2);
   		//获取社区
   		$areaId3 = (int)I("areaId3");
   		$communitys = array();
   		if($areaId3>0){
   		    $communitys = $mcommunitys->getByDistrict($areaId3);
   		}
        $this->assign('communitys',$communitys);

   		//获取商品列表
   		$obj["areaId2"] = $areaId2;
        $obj["areaId3"] = $areaId3;
   		$rslist = $mgoods->getGoodsList($obj);
		$brands = $rslist["brands"];
		$pages = $rslist["pages"];
		$goodsNav = $rslist["goodsNav"];
		$this->assign('goodsList',$rslist);
		//动态划分价格区间
		$maxPrice = $mgoods->getMaxPrice($obj);
		$minPrice = 0;
		$pavg5 = ($maxPrice/5);
		$prices = array();
    	$price_grade = 0.0001;
        for($i=-2; $i<= log10($maxPrice); $i++){
            $price_grade *= 10;
        }
    	//区间跨度
        $span = ceil(($maxPrice - $minPrice) / 8 / $price_grade) * $price_grade;
        if($span == 0){
            $span = $price_grade;
        }
		for($i=1;$i<=8;$i++){
			$prices[($i-1)*$span."_".($span * $i)] = ($i-1)*$span."-".($span * $i);
			if(($span * $i)>$maxPrice) break;
		}
		if(count($prices)<5){
			$prices = array();
			$prices["0_100"] = "0-100";
			$prices["100_200"] = "100-200";
			$prices["200_300"] = "200-300";
			$prices["300_400"] = "300-400";
			$prices["400_500"] = "400-500";
		}
        $this->assign('c1Id',I("c1Id"));
   		$this->assign('c2Id',I("c2Id"));
   		$this->assign('c3Id',I("c3Id"));
   		$this->assign('bs',I("bs",0));
   		$this->assign('msort',I("msort",0));
		$this->assign('sj',I("sj",0));
		$this->assign('stime',I("stime"));//上架开始时间
		$this->assign('etime',I("etime"));//上架结束时间

   		$this->assign('areaId3',I("areaId3",0));
   		$this->assign('communityId',I("communityId",0));

   		$pricelist = explode("_",I("prices"));
   		$this->assign('sprice',$pricelist[0]);
   		$this->assign('eprice',$pricelist[1]);

   		$this->assign('brandId',I("brandId",0));
   		$this->assign('keyWords',urldecode(I("keyWords")));
		$this->assign('brands',$brands);
		$this->assign('goodsNav',$goodsNav);
		$this->assign('pages',$pages);
		$this->assign('prices',$prices);
		$priceId = $prices[I("prices")];
		$this->assign('priceId',(strlen($priceId)>1)?I("prices"):'');
   		$this->assign('districts',$districts);
   		$this->display('goods_list');
    }


	/**
	 * 查询商品详情
	 *
	 */
	public function getGoodsDetails(){

		$goods = D('Home/Goods');
		$kcode = I("kcode");
		$scrictCode = base64_encode(md5("o2omall".date("Y-m-d")));
		//查询商品详情
		$goodsId = (int)I("goodsId");
		$this->assign('goodsId',$goodsId);
		$obj["goodsId"] = $goodsId;
		$goodsDetails = $goods->getGoodsDetails($obj);
		if($kcode==$scrictCode || ($goodsDetails["isSale"]==1 && $goodsDetails["goodsStatus"]==1)){
			if($kcode==$scrictCode){//来自后台管理员
				$this->assign('comefrom',1);
			}

			$shopServiceStatus = 1;
			if($goodsDetails["shopAtive"]==0){
				$shopServiceStatus = 0;
			}
			$goodsDetails["serviceEndTime"] = str_replace('.5',':30',$goodsDetails["serviceEndTime"]);
			$goodsDetails["serviceEndTime"] = str_replace('.0',':00',$goodsDetails["serviceEndTime"]);
			$goodsDetails["serviceStartTime"] = str_replace('.5',':30',$goodsDetails["serviceStartTime"]);
			$goodsDetails["serviceStartTime"] = str_replace('.0',':00',$goodsDetails["serviceStartTime"]);
			$goodsDetails["shopServiceStatus"] = $shopServiceStatus;
			$goodsDetails['goodsDesc'] = htmlspecialchars_decode($goodsDetails['goodsDesc']);


			$areas = D('Home/Areas');
			$shopId = intval($goodsDetails["shopId"]);
			$obj["shopId"] = $shopId;
			$obj["areaId2"] = $this->getDefaultCity();
			$obj["attrCatId"] = $goodsDetails['attrCatId'];
			$shops = D('Home/Shops');
			$shopScores = $shops->getShopScores($obj);
			$this->assign("shopScores",$shopScores);

			$shopCity = $areas->getDistrictsByShop($obj);
			$this->assign("shopCity",$shopCity[0]);

			$shopCommunitys = $areas->getShopCommunitys($obj);
			$this->assign("shopCommunitys",json_encode($shopCommunitys));

			$this->assign("goodsImgs",$goods->getGoodsImgs());
			$this->assign("hotgoods",$goods->getHotGoods($goodsDetails['shopId']));
			$this->assign("relatedGoods",$goods->getRelatedGoods($goodsId));
			$this->assign("goodsNav",$goods->getGoodsNav());
			//获取商品属性价格并累加,商品属性库存取最小值
			$price = 0.0;
			$stock = array();
			$goodsAttrId = array();
			foreach($goods->getAttrs($obj) as $k=>$v){
				if($k=='priceAttrs'){
					foreach($v as $key=>$value){
						foreach($value as $ks=>$vs){
							if(is_numeric($ks) && $vs['isRecomm']==1){
								$price += $vs['attrPrice'];
								$stock[] = $vs['attrStock'];
								$goodsAttrId[] = $vs['id'];
							}
						}
					}
				}
			}
			$stocks = min($stock);

			if($stocks!=0){
				$goodsDetails['goodsStock'] = $stocks;
			}
			if($price!=0){
				$goodsDetails['shopPrice'] = $price;
			}
			$goodsDetails['goodsAttrId'] = $goodsAttrsId;
			$this->assign("goodsAttrs",$goods->getAttrs($obj));
			$this->assign("goodsDetails",$goodsDetails);
			$viewGoods = cookie("viewGoods");
					$sql = "select id,attrPrice,attrStock from  __PREFIX__goods_attributes where goodsId=".$goodsId;
			if(!in_array($goodsId,$viewGoods)){
				$viewGoods[] = $goodsId;
			}
			if(!empty($viewGoods)){
				cookie("viewGoods",$viewGoods,25920000);
			}
			//获取关注信息
			$m = D('Home/Favorites');
			$this->assign("favoriteGoodsId",$m->checkFavorite($goodsId,0));
			$m = D('Home/Favorites');
			$this->assign("favoriteShopId",$m->checkFavorite($shopId,1));
			//客户端二维码
		$this->assign("qrcode",base64_encode("{type:'goods',content:'".$goodsId."',key:'wstmall'}"));
			$this->display('goods_details');
		}else{
			$this->display('goods_notexist');
		}

	}

	/**
	 * 获取商品库存
	 *
	 */
	public function getGoodsStock(){
		$data = array();
		$data['goodsId'] = (int)I('goodsId');
		$data['isBook'] = (int)I('isBook');
		$data['goodsAttrId'] = (int)I('goodsAttrId');
		$data['isGroup'] = (int)I('isGroup');
		$data['isSeckill'] = (int)I('isSeckill');
		$goods = D('Home/Goods');
		$goodsStock = $goods->getGoodsStock($data);
		echo json_encode($goodsStock);

	}

	/**
	 * 获取服务社区
	 *
	 */
	public function getServiceCommunitys(){

		$areas = D('Home/Areas');
		$serviceCommunitys = $areas->getShopCommunitys();
		echo json_encode($serviceCommunitys);
	}

   /**
	* 分页查询-出售中的商品
	*/
	public function queryOnSaleByPage(){
		$this->isShopLogin();
		$USER = session('WST_USER');
		//获取商家商品分类
		$m = D('Home/ShopsCats');
		$this->assign('shopCatsList',$m->queryByList($USER['shopId'],0));
		$m = D('Home/Goods');
    	$page = $m->queryOnSaleByPage($USER['shopId']);
    	$pager = new \Think\Page($page['total'],$page['pageSize']);
    	$page['pager'] = $pager->show();
    	$this->assign('Page',$page);
    	$this->assign("umark","queryOnSaleByPage");
    	$this->assign("shopCatId2",I('shopCatId2'));
    	$this->assign("shopCatId1",I('shopCatId1'));
    	$this->assign("goodsName",urldecode(I('goodsName')));
        $this->display("Shops/goods/list_onsale");
	}

    /**
     * 分页查询-通过审核的商品
     */
    public function queryPassGoodsByPage(){
        $this->isShopLogin();
        $USER = session('WST_USER');
        //获取商家商品分类
        $m = D('Home/ShopsCats');
        $this->assign('shopCatsList',$m->queryByList($USER['shopId'],0));
        $m = D('Home/Goods');
        $page = $m->queryPassGoodsByPage($USER['shopId']);
        $pager = new \Think\Page($page['total'],$page['pageSize']);
        $page['pager'] = $pager->show();
        $this->assign('Page',$page);
        $this->assign("umark","queryPassGoodsByPage");
        $this->assign("shopCatId2",I('shopCatId2'));
        $this->assign("shopCatId1",I('shopCatId1'));
        $this->assign("goodsName",urldecode(I('goodsName')));
        $this->display("Shops/goods/list_passGoods");
    }
   /**
	* 分页查询-仓库中的商品
	*/
	public function queryUnSaleByPage(){
		$this->isShopLogin();
		$USER = session('WST_USER');
		//获取商家商品分类
		$m = D('Home/ShopsCats');
		$this->assign('shopCatsList',$m->queryByList($USER['shopId'],0));
		$m = D('Home/Goods');
    	$page = $m->queryUnSaleByPage($USER['shopId']);
    	$pager = new \Think\Page($page['total'],$page['pageSize']);
    	$page['pager'] = $pager->show();
    	$this->assign('Page',$page);
    	$this->assign("umark","queryUnSaleByPage");
    	$this->assign("shopCatId2",I('shopCatId2'));
    	$this->assign("shopCatId1",I('shopCatId1'));
    	$this->assign("goodsName",urldecode(I('goodsName')));
        $this->display("Shops/goods/list_unsale");
	}
   /**
	* 分页查询-在审核中的商品
	*/
	public function queryPenddingByPage(){
		$this->isShopLogin();
		$USER = session('WST_USER');
		//获取商家商品分类
		$m = D('Home/ShopsCats');
		$this->assign('shopCatsList',$m->queryByList($USER['shopId'],0));
		$m = D('Home/Goods');
    	$page = $m->queryPenddingByPage($USER['shopId']);
    	$pager = new \Think\Page($page['total'],$page['pageSize']);
    	$page['pager'] = $pager->show();
    	$this->assign('Page',$page);
    	$this->assign("umark","queryPenddingByPage");
    	$this->assign("shopCatId2",I('shopCatId2'));
    	$this->assign("shopCatId1",I('shopCatId1'));
    	$this->assign("goodsName",urldecode(I('goodsName')));
        $this->display("Shops/goods/list_pendding");
	}
	/**
	 * 跳到新增/编辑商品
	 */
    public function toEdit(){
		$this->isShopLogin();
		$USER = session('WST_USER');
		//获取商品分类信息
		$m = D('Home/GoodsCats');
		$this->assign('goodsCatsList',$m->queryByList());
		//获取商家商品分类
		$m = D('Home/ShopsCats');
		$this->assign('shopCatsList',$m->queryByList($USER['shopId'],0));

		//获取商品类型
		$m = D('Home/AttributeCats');
		$this->assign('attributeCatsCatsList',$m->queryByList());
		$m = D('Home/Goods');

        $agent =D('Home/Agent');
        $agentStatus   =    $agent->getShopAgent();
		$object = array();


    	if(I('id',0)>0){
    		$object = $m->get();
    	}else{
    		$object = $m->getModel();
    	}
        $this->assign('agentStatus',$agentStatus);
    	$this->assign('object',$object);
    	$this->assign("umark",I('umark'));
        $this->display("Shops/goods/edit");
	}
    /**
     * 跳到新增/编辑拍卖商品
     */
    public function toEditAuctionGoods(){
        $this->isShopLogin();
        $USER = session('WST_USER');
        //获取商品分类信息
        $m = D('Home/GoodsCats');
        $this->assign('goodsCatsList',$m->queryByList());
        //获取商家商品分类
        $m = D('Home/ShopsCats');
        $this->assign('shopCatsList',$m->queryByList($USER['shopId'],0));

        //获取商品类型
        $m = D('Home/AttributeCats');
        $this->assign('attributeCatsCatsList',$m->queryByList());
        $m = D('Home/Goods');

        $agent =D('Home/Agent');
        $agentStatus   =    $agent->getShopAgent();
        $object = array();


        if(I('id',0)>0){
            $object = $m->getAuctionGoods();
        }else{
            $object = $m->getModel();
        }
        $this->assign('agentStatus',$agentStatus);
        $this->assign('object',$object);
        $this->assign("umark",I('umark'));
        $this->display("Shops/goods/editAuction");
    }
	/**
	 * 新增商品
	 */
	public function edit(){
		$this->isShopLogin();
		$m = D('Home/Goods');
    	$rs = array();

    	if((int)I('id',0)>0){
    		$rs = $m->edit();
    	}else{
    		$rs = $m->insert();
    	}
    	$this->ajaxReturn($rs);
	}
    /**
     * 新增商品
     */
    public function editAuctionGoods(){
        $this->isShopLogin();
        $m = D('Home/Goods');
        $rs = array();
        if((int)I('id',0)>0){
            $rs = $m->editAuctionGoods();
        }else{
           // $rs = $m->insert();
        }
        $this->ajaxReturn($rs);
    }
	/**
	 * 删除商品
	 */
	public function del(){
		$this->isShopLogin();
		$m = D('Home/Goods');
		$rs = $m->del();
		$this->ajaxReturn($rs);
	}
	/**
	 * 批量设置商品状态
	 */
	public function goodsSet(){
		$this->isShopLogin();
		$m = D('Home/Goods');
		$rs = $m->goodsSet();
		$this->ajaxReturn($rs);
	}
	/**
	 * 批量删除商品
	 */
	public function batchDel(){
		$this->isShopLogin();
		$m = D('Home/Goods');
		$rs = $m->batchDel();
		$this->ajaxReturn($rs);
	}
	/**
	 * 修改商品上架/下架状态
	 */
	public function sale(){
		$this->isShopLogin();
		$m = D('Home/Goods');
		$rs = $m->sale();
		$this->ajaxReturn($rs);
	}
	/**
	 * 核对商品信息
	 */
	public function checkGoodsStock(){
		$m = D('Home/Goods');
		$totalMoney = 0;
		$shopcart = session("WST_CART")?session("WST_CART"):array();
		$catgoods = array();
		foreach($shopcart as $key=>$cgoods){
			$temp = explode('_',$key);
			//获取团购标志
			$isGroup = $temp[count($temp)-1];
			//去除末尾团购标志
			array_pop($temp);
			$goodsAttrIds = array();
			foreach($temp as $k=>$v) {
				if ($k == 0) {
					$goodsId = (int)$v;
				} else {
					$goodsAttrIds[] = (int)$v;
				}
			}
			$goodsAttrId = implode(',', $goodsAttrIds);
			$goods = $m->getGoodsInfo((int)$temp[0],$goodsAttrId,$isGroup);
			if($goods["isBook"]==1){
				$goods["goodsStock"] = $goods["goodsStock"]+$goods["bookQuantity"];
			}
			$goods["cnt"] = $cgoods["cnt"];
			$totalMoney += $goods["cnt"]*$goods["shopPrice"];
			$catgoods[] = $goods;
		}
		$this->ajaxReturn($catgoods);
	}

	/**
	 * 获取验证码
	 */
	public function getGoodsVerify(){
		$data = array();
		$data["status"] = 1;
		$verifyCode = base64_encode(md5("o2omall".date("Y-m-d")));
		$data["verifyCode"] = $verifyCode;
		$this->ajaxReturn($data);
	}

	/**
	 * 查询商品属性价格及库存
	 */
    public function getPriceAttrInfo(){
    	$goods = D('Home/Goods');
		$rs = $goods->getPriceAttrInfo();
		$this->ajaxReturn($rs);
    }
    //秒杀专用 0506
    public function getPriceAttrInfoSk(){
        $goods = D('Home/Goods');
        $rs = $goods->getPriceAttrInfoSk();
        $this->ajaxReturn($rs);
    }
	/**
	 * 修改商品库存
	 */
    public function editStock(){
    	$this->isShopLogin();
    	$m = D('Home/Goods');
    	$rs = $m->editStock();
    	$this->ajaxReturn($rs);
    }

    /**
     * 修改商品库存,商品编号,价格
     */
    public function editGoodsBase(){
    	$this->isShopLogin();
    	$m = D('Home/Goods');
    	$rs = $m->editGoodsBase();
    	$this->ajaxReturn($rs);
    }

    /**
     * 获取商品搜索提示列表
     */
    public function getKeyList(){
    	$m = D('Home/Goods');
    	$rs = $m->getKeyList();
    	$this->ajaxReturn($rs);
    }

    /**
     * 修改 推荐/精品/新品/热销/上架
     */
    public function changSaleStatus(){
    	$this->isShopLogin();
    	$m = D('Home/Goods');
    	$rs = $m->changSaleStatus();
    	$this->ajaxReturn($rs);
    }

    /**
     * 上传商品数据
     */
    public function importGoods(){
    	$this->isShopLogin();
    	$config = array(
		        'maxSize'       =>  0, //上传的文件大小限制 (0-不做限制)
		        'exts'          =>  array('xls','xlsx','xlsm'), //允许上传的文件后缀
		        'rootPath'      =>  './Upload/', //保存根路径
		        'driver'        =>  'LOCAL', // 文件上传驱动
		        'subName'       =>  array('date', 'Y-m'),
		        'savePath'      =>  I('dir','uploads')."/"
		);
		$upload = new \Think\Upload($config);
		$rs = $upload->upload($_FILES);
		$rv = array('status'=>-1);
		if(!$rs){
			$rv['msg'] = $upload->getError();
		}else{
			$m = D('Home/Goods');
    	    $rv = $m->importGoods($rs);
		}
    	$this->ajaxReturn($rv);
    }

}